package com.zhy.baselibrary.utils.span;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ReplacementSpan;

import com.blankj.utilcode.util.SizeUtils;

class BackgroundImageSpan extends ReplacementSpan {

    private Drawable mDrawable;

    public BackgroundImageSpan(Drawable drawable) {
        this.mDrawable = drawable;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        // 获取文字的宽度
        Rect bounds = new Rect();
        paint.getTextBounds(text.toString(), start, end, bounds);
        int width = bounds.width();

        // 设置 Drawable 的边界
        mDrawable.setBounds(0, 0, width+ SizeUtils.dp2px(10f), bounds.height()+SizeUtils.dp2px(10f));

        return width;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        // 绘制背景图片
        canvas.save();
        canvas.translate(x, top);
        mDrawable.draw(canvas);
        canvas.restore();

        // 绘制文字
        paint.setColor(Color.parseColor("#FFFFFF"));
        paint.setTextSize(SizeUtils.dp2px(16f));
//        int width = canvas.getWidth();
//        int height = canvas.getHeight();
//        // 计算文本的基线位置
//        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
//        float baseline = height / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
        canvas.drawText(text, start, end, x+SizeUtils.dp2px(4f), y+SizeUtils.dp2px(1f), paint);
    }
}
